package com.cloud.school.bus.teacherhelper.modules.notice;

import java.util.ArrayList;
import java.util.List;

import android.R.anim;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshListView;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase.Mode;
import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.popupwindow.CustomPopupWindow;
import com.android.support.jhf.utils.ClipboardUtils;
import com.android.support.jhf.utils.ToolUtils;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.slidingfragment.BaseAboveFragment;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Notice;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.home.BigPictureActivity;
import com.cloud.school.bus.teacherhelper.modules.information.adapter.InformationAdapter;
import com.cloud.school.bus.teacherhelper.modules.notice.adapter.NoticeAdapter;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadFileUtils;
import com.cloud.school.bus.teacherhelper.protocol.notice.GetNoticeListRequest;
import com.cloud.school.bus.teacherhelper.protocol.notice.GetNoticeListResponse;

/**
 * 家长通知
 * 
 * @author lenovo
 * 
 */
public class NoticeFragment extends BaseAboveFragment {

	private PullToRefreshListView mPullToRefreshListView;
	private NoticeAdapter mNoticeAdapter;
	private ViewGroup mNoDataLayout;

	private String mLastStartTime = "0";
	private List<Notice> mNotices = new ArrayList<Notice>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(R.layout.fragment_notice, null);
		setViewData(view);
		return view;
	}

	@Override
	protected void setViewData(View view) {
		mPullToRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.listView);
		ListView listView = mPullToRefreshListView.getRefreshableView();
		listView.setDivider(getResources().getDrawable(android.R.color.transparent));
		listView.setDividerHeight(10);
		mPullToRefreshListView.setMode(Mode.BOTH);
		mNoticeAdapter = new NoticeAdapter(mParentContext, mNotices);
		mPullToRefreshListView.setAdapter(mNoticeAdapter);

		mNoDataLayout = (ViewGroup)view.findViewById(R.id.noDataLayout);
		
		setTitleNavBar(view);
		setListener(view);

		getNoticeList(false);
	}

	@Override
	protected void setListener(View view) {

		mPullToRefreshListView
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						Intent intent = new Intent(mParentContext,
								NoticeDetailActivity.class);
						intent.putExtra("Notice", mNotices.get(arg2));
						startActivity(intent);
					}
				});
		
		mPullToRefreshListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Notice notice = mNotices.get(arg2);
				
				copyContentDialog(notice.noticecontent, arg1);
				return false;
			}
		});

		mPullToRefreshListView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						getNoticeList(false);
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								mPullToRefreshListView.onRefreshComplete();
							}
						});
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						getNoticeList(true);
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								mPullToRefreshListView.onRefreshComplete();
							}
						});
					}
				});
	}

	@Override
	protected void setTitleNavBar(View view) {
		TitleNavBarView titleNavBarView = (TitleNavBarView) view
				.findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage(getString(R.string.notice));
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				((SlidingActivity) mParentContext).toggle();
			}
		});
		titleNavBarView.setRightButtonImageString(R.drawable.btn_notice_edit_xml, "",
				R.color.btn_bg_blue);
		titleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mParentContext,
						ParentNoticeActivity.class);
				startActivityForResult(intent, 0);
			}
		});
	}

	private void getNoticeList(final boolean moreFlag) {
		if (!moreFlag) {
			mLastStartTime = "0";
		}
		NetworkClient.getNetworkClient().GetRequest(
				new GetNoticeListRequest(mParentContext, mLastStartTime, "0"),
				new GetNoticeListResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						if ("1".equals(code)) {
							HandlerPostUI.getHandlerPostUI(new Runnable() {

								@Override
								public void run() {
									if (0 != noticeList.size()) {
										mLastStartTime = noticeList.get(noticeList.size()-1).addtime;
									}
									if (moreFlag) {
										// 更多
										if (0 != mNotices.size()) {
											mNotices.addAll(noticeList);
											mNoticeAdapter
													.notifyDataSetChanged();
										} else {
											HandlerToastUI.getHandlerToastUI(
													mParentContext, getString(R.string.no_more_information));
										}
									} else {
										// 刷新
										mNotices.clear();
										mNotices.addAll(noticeList);
										mNoticeAdapter.notifyDataSetChanged();
										
										if(0 == mNotices.size()){
											mNoDataLayout.setVisibility(View.VISIBLE);
											mPullToRefreshListView.setVisibility(View.GONE);
										}else {
											mNoDataLayout.setVisibility(View.GONE);
											mPullToRefreshListView.setVisibility(View.VISIBLE);
										}
									}
								}
							});

							DebugLog.logI(noticeList.toString());
						} else if ("-2".equals(code)) {
							HandlerToastUI.getHandlerToastUI(mParentContext,
									"无内容");
						}
					}
				});
	}
	
	private void copyContentDialog(final String contentString, final View anchor) {
		final CustomPopupWindow customPopupWindow = new CustomPopupWindow(
				mParentContext);
		View view = LayoutInflater.from(mParentContext).inflate(
				R.layout.popup_letter_content_copy, null);
		ViewGroup copyLayout = (ViewGroup) view.findViewById(R.id.copyLayout);
		copyLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ClipboardUtils.copy(contentString, mParentContext);
				customPopupWindow.dismiss();
			}
		});
		int width = ToolUtils.dipToPx(mParentContext, 50);
		int height = ToolUtils.dipToPx(mParentContext, 50);
		customPopupWindow.setContentView(view, width, height);
		customPopupWindow.show(anchor, anchor.getWidth() / 2 - width / 2,
				-anchor.getHeight() - height);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 发布家长通知返回
			switch (resultCode) {
			case Activity.RESULT_OK: {
				getNoticeList(false);
				break;
			}
			case Activity.RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}
	
	/**
	 * 判断网络连接监听
	 */
	private BroadcastReceiver mNetConnectBroadcastReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
				UploadFileUtils.getUploadUtils().setContext(mParentContext);
				UploadFileUtils.getUploadUtils().setFragment(mFragment);
				UploadFileUtils.getUploadUtils().uploadFileService();
			}
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		// 注册广播
		IntentFilter netConnectIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
		mParentContext.registerReceiver(mNetConnectBroadcastReceiver, netConnectIntentFilter);
	}

	@Override
	public void onPause() {
		super.onPause();
		mParentContext.unregisterReceiver(mNetConnectBroadcastReceiver);
	}
}
